package com.lzq.concurrent.interrupt;

/**
 * @Author:
 * @Description: jdk内置锁不能被中断
 * @Date: Created in : 2018/10/4 下午11:34
 **/

/**
 * 执行结果：
 * start t1
 * start t2
 * before interrupt
 * end interrupt
 *
 * 这就可以证明 synchronize 不可被中断了：
 * t1 线程执行到完start t1 并完成 1 秒睡眠，等待 o2 的锁，
 * 而此时 o2 的锁被 t2 拿着，t2 又在等 o1 的锁
 * 如果 synchronize 锁能被中断，那执行 t1.interrupt() 的时候就会被中断并且让出 o1 的锁，
 * 就能让 t2 继续执行下去，实际上是执行会被卡住，t2 并没有继续向下执行，所以可得出结论，synchronize 不会被中断
 */
public class Uninterruptible {
    private static final Object o1 = new Object();
    private static final Object o2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        t2.start();
        Thread.sleep(2000);
        System.out.println("before interrupt");
        t1.interrupt();
        t2.interrupt();
        System.out.println("end interrupt");
        t1.join();
        t2.join();
    }

    static Thread t1 = new Thread(() -> {
        synchronized (o1){
            try {
                System.out.println("start t1");
                Thread.sleep(1000);
                synchronized (o2){
                    System.out.println("t1 lock o2");
                }
            } catch (InterruptedException e) {
                System.out.println("t1 interrupted");
                e.printStackTrace();
            }
        }
    });

    static Thread t2 = new Thread(() -> {
        synchronized (o2){
            try {
                System.out.println("start t2");
                Thread.sleep(1000);
                synchronized (o1){
                    System.out.println("t2 lock o1");
                }
            } catch (InterruptedException e) {
                System.out.println("t2 intterrupted");
                e.printStackTrace();
            }
        }
    });
}